package com.zygame.sdk.view;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.RemoteException;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.vending.billing.IInAppBillingService;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.Scopes;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Scope;
import com.google.android.gms.common.api.Status;
import com.zygame.sdk.R;
import com.zygame.sdk.ZyGameSDK;
import com.zygame.sdk.adapter.ListAdapter;
import com.zygame.sdk.adapter.PurchaseAdapter;
import com.zygame.sdk.model.UserModel;
import com.zygame.sdk.utils.LoginUtil;
import com.zygame.sdk.utils.SharedPreferencesHelper;
import com.zygame.sdk.utils.http.HttpUtil;
import com.zygame.sdk.utils.http.NetHttpUtil;
import com.zygame.sdk.utils.log.LogHelper;
import com.zygame.sdk.utils.res.ResourceUtil;
import com.zygame.sdk.utils.toast.ToastUtil;
import com.zygame.sdk.utils.util.IabHelper;
import com.zygame.sdk.utils.util.IabResult;
import com.zygame.sdk.utils.util.Inventory;
import com.zygame.sdk.utils.util.Purchase;
import com.zygame.sdk.utils.util.SkuDetails;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by YuXL on 2017/11/2.
 */

public class Zy_GooglePay extends FragmentActivity implements View.OnClickListener, GoogleApiClient.OnConnectionFailedListener {
    private static final String TAG = "googlePay";
    private GoogleSignInOptions gso;
    private GoogleApiClient mGoogleApiClient;
    private static final int RC_SIGN_IN = 10001;
    private JSONObject jsonObject;
    private String base64EncodedPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlMQr2IT+zuel351J7RGX/73YAlo+0ro5HPdJeGfyWIVmjYNZb7v6uDer95/p2Kh4/IkITKBWJssDLkELeqz7NPkTEW4wnjfFuZxQih4f9laTELxHR+9bITpVJ1im/GRDQmsCPunm9A46CWSTb6gYbFuOKcbEE9avyVK0Wc0Ce+eZak5Lsziw+Qu/4qEosQ6ZJTsDdgnVmz00m6GATeOM1yRXWMPMzZc0nZPXVYKUvkfrw88fTtw26EUnUhUM0sPs04QOR6JSf0EPovwRsMVe9JRadasl/73j6Bp9VpweLr903w7nmXR6C/Y1YVfdSQSVvCSY8UvsyRKetXjoScaO5wIDAQAB";
    private IabHelper mHelper;
    IInAppBillingService mService;
    static final String SKU_PREMIUM = "premium";
    private Purchase toConsumePurchase;
    private String toConsumePurchaseJson = "{\"orderId\":\"GPA.3313-4049-4094-19093\",\"packageName\":\"com.zy_demo\",\"productId\":\"p2\",\"purchaseTime\":1552546547564,\"purchaseState\":0,\"purchaseToken\":\"haaoieckfakcibdnopiemnpm.AO-J1OxX6BMlnNIG5tSQEK2wa5qHQ_Ci87TjD5OWLAYG99FZS4VT8itTCFc50TBis20ouLHeBn8ibcZph478J8ALWNJqu_ZUdg\"}";


    private ListView listViewInApp;
    private ListView listViewInAppPurchase;
    private ListView listViewSubs;
    private ListView listViewSubsPurchase;

    private ImageView ivHead;
    private TextView tvName;
    private TextView tvId;
    private TextView tvEmail;

    private List<SkuDetails> mInAppDatas = new ArrayList<>();
    private List<Purchase> mPurchaseInAppDatas = new ArrayList<>();
    private List<SkuDetails> mSUBSDatas = new ArrayList<>();
    private List<Purchase> mPurchaseSUBSDatas = new ArrayList<>();

    private ListAdapter mInAppListAdapter;
    private PurchaseAdapter mPurchaseInAppAdapter;
    private ListAdapter mSubsListAdapter;
    private PurchaseAdapter mPurchaseSubsAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(ResourceUtil.getLayoutId(this, "zy_pay"));
        findViewById(ResourceUtil.getId(this, "btn_pay")).setOnClickListener(this);
        findViewById(ResourceUtil.getId(this, "btn_login")).setOnClickListener(this);
        findViewById(ResourceUtil.getId(this, "btn_consume")).setOnClickListener(this);


//        FacebookSdk.sdkInitialize(this);



        ivHead = (ImageView) findViewById(R.id.iv_head);
        tvName = (TextView) findViewById(R.id.tv_name);
        tvId = (TextView) findViewById(R.id.tv_id);
        tvEmail = (TextView) findViewById(R.id.tv_email);

        listViewInApp = (ListView) findViewById(R.id.listView1);
        listViewInAppPurchase = (ListView) findViewById(R.id.listView2);
        listViewSubs = (ListView) findViewById(R.id.listView3);
        listViewSubsPurchase = (ListView) findViewById(R.id.listView4);

        //一次性商品
        mInAppListAdapter = new ListAdapter(mInAppDatas, 1);
        listViewInApp.setAdapter(mInAppListAdapter);
        //已购买的一次性商品
        mPurchaseInAppAdapter = new PurchaseAdapter(mPurchaseInAppDatas, 1);
        listViewInAppPurchase.setAdapter(mPurchaseInAppAdapter);
        //订阅类型商品
        mSubsListAdapter = new ListAdapter(mSUBSDatas, 2);
        listViewSubs.setAdapter(mSubsListAdapter);
        //已订阅商品
        mPurchaseSubsAdapter = new PurchaseAdapter(mPurchaseSUBSDatas, 2);
        listViewSubsPurchase.setAdapter(mPurchaseSubsAdapter);

        addItemListener();


        gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestScopes(new Scope(Scopes.DRIVE_APPFOLDER))
                .requestEmail()
                .requestServerAuthCode("103357724928-kf669t8phog6m269i1pconeebotgd1n8.apps.googleusercontent.com")
                .build();

        /* FragmentActivity *//* OnConnectionFailedListener */
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();


        mHelper = new IabHelper(this, base64EncodedPublicKey);
        mHelper.enableDebugLogging(true);
        mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
            public void onIabSetupFinished(IabResult result) {
                Log.d("sss", "Setup finished.");

                if (!result.isSuccess()) {
                    Toast.makeText(Zy_GooglePay.this, result.getMessage(), Toast.LENGTH_SHORT).show();
                    return;
                }

                if (mHelper == null)
                    return;
                Toast.makeText(Zy_GooglePay.this, "成功", Toast.LENGTH_SHORT).show();

                try {
                    //查询所有商品
                    queryAllSkudetails();

                    //查询已购买的商品
                    queryPurchaseProducts("inapp");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    /**
     * 查询已购买的商品
     *
     * @param itemType 商品类型
     */
    private void queryPurchaseProducts(String itemType) {
        try {
            Inventory inventory = new Inventory();
            int success = mHelper.queryPurchases(inventory, itemType);
            if (success == 0) {
                mPurchaseInAppDatas.clear();
                if (inventory.getAllPurchases() != null) {
                    mPurchaseInAppDatas.addAll(inventory.getAllPurchases());
                    mPurchaseInAppAdapter.notifyDataSetChanged();
                    setListViewHeightBasedOnChildren(listViewInAppPurchase);

                    Log.i("GD", "inventory.getAllPurchases(): " + inventory.getAllPurchases().toString());

                    for (int i = 0; i < inventory.getAllPurchases().size(); i++) {
                        Purchase purchaseStr = inventory.getAllPurchases().get(i);
                        Bundle paramsData = new Bundle();
                        paramsData.putString("notificationId", "");
                        paramsData.putString("orderId", purchaseStr.getOrderId());
                        paramsData.putString("productId", purchaseStr.getSku());
                        paramsData.putString("purchaseState",
                        purchaseStr.getPurchaseState() + "");
                        paramsData.putString("purchaseTime",
                        purchaseStr.getPurchaseTime() + "");
                        paramsData.putString("sdkOrderId",
                        purchaseStr.getDeveloperPayload());
                        paramsData.putString("signature", purchaseStr.getSignature());
                        paramsData.putString("amount", "");
                        paramsData.putString("price", "");
                        paramsData.putString("inappPurchaseData", purchaseStr.getOriginalJson());
                        //HuowuSdk.getInstance().googlePayCheck(activity,
                        //         paramsData, new InternalCallback() {
                        //             public void onResult(int errorCode, Bundle data) {
                        //                 Toast.makeText(activity, "SUCCESS", Toast.LENGTH_SHORT).show();
                        //                 if (errorCode == ErrorCode.SUCCESS) {
                        //                     Message msg = new Message();
                        //                     msg.what = 3;
                        //                     handlerResult.sendMessage(msg);
                        //                 }
                        //             }
                        //         }
                        // );
                    }
                }
                //handlerResult.sendEmptyMessage(3);
                //mHelper.dispose();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    private void queryAllSkudetails() throws IabHelper.IabAsyncInProgressException {
        //查询所有商品
        mHelper.queryInventoryAsync(true, Arrays.asList("p1", "p4", "p3"), Arrays.asList("p1"), new IabHelper.QueryInventoryFinishedListener() {
            @Override
            public void onQueryInventoryFinished(IabResult result, Inventory inv) {
                Log.i("GD", "queryInventoryAsync -----: " + inv.getAllSkudetails(new String[]{"p1", "p4", "p3"}).toString());
                List<SkuDetails> skuDetailsList = inv.getAllSkudetails(new String[]{"p1", "p4", "p3"});
                mInAppDatas.addAll(skuDetailsList);
                mInAppListAdapter.notifyDataSetChanged();
                setListViewHeightBasedOnChildren(listViewInApp);
            }
        });
    }


    private void addItemListener() {
        listViewInApp.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            //------------购买
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (mInAppDatas.size() > 0) {
                    SkuDetails skuDetails = mInAppDatas.get(i);
                    try {
                        mHelper.launchPurchaseFlow(Zy_GooglePay.this, skuDetails.getSku(), 1, mPurchaseFinishedListener);
                    } catch (IabHelper.IabAsyncInProgressException e) {
                        e.printStackTrace();
                    }
                }
            }
        });


        listViewInAppPurchase.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            //-------------消费
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Purchase purchase = mPurchaseInAppDatas.get(i);
                try {
                    mHelper.consumeAsync(purchase, mConsumeFinishedListener);
                } catch (IabHelper.IabAsyncInProgressException e) {
                    e.printStackTrace();
                }
            }
        });

        listViewSubs.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (mSUBSDatas.size() > 0) {
                    SkuDetails skuDetails = mSUBSDatas.get(i);
                    try {
                        mHelper.launchPurchaseFlow(Zy_GooglePay.this, skuDetails.getSku(), 1, mPurchaseFinishedListener);
                    } catch (IabHelper.IabAsyncInProgressException e) {
                        e.printStackTrace();
                    }
                }
            }
        });


        listViewSubsPurchase.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            //-------------取消订阅
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Purchase purchase = mPurchaseSUBSDatas.get(i);
                ToastUtil.showToast(Zy_GooglePay.this, "不可取消订阅");
            }
        });
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == ResourceUtil.getId(Zy_GooglePay.this, "btn_login")) {
            signIn();
        } else if (id == ResourceUtil.getId(Zy_GooglePay.this, "btn_pay")) {
            try {
                /*购买商品时也需要product ID，调用launchPurchaseFlow(Activity, String, int, OnIabPurchaseFinishedListener, String)
                Activity：调用launchPurchaseFlow的activity
                String：product ID，确保是ID而不是商品名称
                Int：request code值，可以是任何正整数，Google Play会将该值随购买的回复一起返回给Activity的onActivityResult
                OnIabPurchaseFinishedListener：购买请求完成的监听器
                String：字符串标记，惟一的标示购买请求，可以为空。如果你指定一个字符串值,谷歌将返回此字符串以及购买响应。在实际项目中最好由服务器随机生成一个字符串使用*/
                mHelper.launchPurchaseFlow(this, "p2", 1, mPurchaseFinishedListener);
            } catch (IabHelper.IabAsyncInProgressException e) {
                complain("Error launchingng purchase flow. Another async operation in progress.");
            }
        } else if (id == ResourceUtil.getId(Zy_GooglePay.this, "btn_consume")) {
            try {
                //购买完成立刻消费
                toConsumePurchase = new Purchase("inapp", toConsumePurchaseJson, "");
                mHelper.consumeAsync(toConsumePurchase, mConsumeFinishedListener);
            } catch (IabHelper.IabAsyncInProgressException | JSONException e) {
                complain("Error consuming gas. Another async operation in progress.");
                //setWaitScreen(false);
                return;
            }
        }
    }

    private void signIn() {
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Log.d(TAG, "onActivityResult(" + requestCode + "," + resultCode + "," + data);
        if (mHelper == null)
            return;

        // Pass on the activity result to the helper for handling
        if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
            // not handled, so handle it ourselves (here's where you'd
            // perform any handling of activity results not related to in-app
            // billing...
            super.onActivityResult(requestCode, resultCode, data);
        } else {
            Log.d(TAG, "onActivityResult handled by IABUtil.");
        }


        // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
        //google id
        //login   -> username == password
        //username == password

        //自动登录  google登录
        //username == password   google id
        //type = 1

        //type == 2 ||type == 1
        if (requestCode == RC_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            Log.i("gd", "status: " + result.getStatus().toString()  + "  code: " + result.getStatus().getStatusCode());
            if (result.isSuccess()) {
                // Google Sign In was successful, authenticate with Firebase
                ToastUtil.showToast(this,"Google登录成功");
                GoogleSignInAccount account = result.getSignInAccount();

                if(account == null){
                    ToastUtil.showToast(this,"获取信息失败,请重试");
                    return;
                }
                updateUI(account);


                String zy_gmail = SharedPreferencesHelper.getInstance().getZY_GMAIL(this);
                String token = SharedPreferencesHelper.getInstance().getToken(this);

                jsonObject = null;
                try {
                    jsonObject = new JSONObject();
                    jsonObject.put("userID", account.getId());
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                HttpUtil.login("", "", account.getServerAuthCode(), "5", "", this, onLoginCallback);
                //firebaseAuthWithGoogle(account);
            } else {
                ToastUtil.showToast(Zy_GooglePay.this, "Google登录失败 code: " + result.getStatus().getStatusCode());
                // Google Sign In failed, update UI appropriately
                // ...
            }
        }
    }


    private void updateUI(GoogleSignInAccount account) {
        tvName.setText("name:  " + account.getDisplayName());
        tvEmail.setText("email:  " + account.getEmail());
        tvId.setText("id:  " + account.getId());
        Glide.with(this).applyDefaultRequestOptions(RequestOptions.circleCropTransform()).load(account.getPhotoUrl()).into(ivHead);
    }


    private void signOut(){
        PendingResult<Status> statusPendingResult = Auth.GoogleSignInApi.signOut(mGoogleApiClient);
        statusPendingResult.setResultCallback(new ResultCallback<Status>() {
            @Override
            public void onResult(@NonNull Status status) {
                Log.i("GD", "status: " + status.toString());
                Log.i("GD", "getStatusCode: " + status.getStatusCode());
                Log.i("GD", "getStatusMessage: " + status.getStatusMessage());
            }
        });
    }


    NetHttpUtil.DataCallback<JSONObject> onLoginCallback = new NetHttpUtil.DataCallback<JSONObject>() {

        @Override
        public void callbackSuccess(JSONObject paramObject) {
//            LogHelper.i("login接口", paramObject.toString());
            Log.i("GD", "login success: " + paramObject.toString());
            String code = paramObject.optString("code");

            if (code.equals("0")) {
                String user_name = paramObject.optString("user_name");
                LoginUtil.loginResult(user_name, user_name, paramObject, Zy_GooglePay.this, SharedPreferencesHelper.getInstance().getZY_GMAIL(Zy_GooglePay.this), 1, jsonObject.toString());
                ZyGameSDK.getInstance().onLoginResult(UserModel.getInstance());
                //mContext.getSharedPreferences("tokeninfo", 0).edit().putString("login_token",paramObject.optString("login_token")).commit();

            } else {
//                ToastUtil.showToast(Zy_GooglePay.this, paramObject.optString("message"));
            }
        }

        @Override
        public void callbackError(String error) {
            LogHelper.i("login接口", error);
            //ZyGameSDK.getInstance().onResult(CmCode.CODE_LOGIN_FAIL, "65 sdk login fail !");
        }

    };

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHelper != null) {
            mHelper.disposeWhenFinished();
            mHelper = null;
        }
    }


    // Callback for when a purchase is finished
    /**
     * 购买完成
     *
     * @param result   购买状态
     * @param purchase 购买的商品
     */
    IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
        public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
            Log.d(TAG, "Purchase finished: " + result.toString() + ", purchase: " + purchase);
            Log.i("gd", "result: " + result.toString());
            Log.i("gd", "result.getResponse: " + result.getResponse());
            // if we were disposed of in the meantime, quit.
            if (mHelper == null)
                return;

            if (result.isFailure()) {
                complain("Error purchasing: " + result.getMessage());
                //setWaitScreen(false);
                return;
            }
            if (!verifyDeveloperPayload(purchase)) {
                //complain("Error purchasing. Authenticity verification failed.");
                //setWaitScreen(false);
                return;
            }

            queryPurchaseProducts("inapp");

            Log.d(TAG, "Purchase successful.");
            //                        if (purchase.getSku().equals("p1")) {
            //                            // bought 1/4 tank of gas. So consume it.
            //                            Log.d(TAG, "Purchase is gas. Starting gas consumption.");
            //                            try {
            //                                //购买完成立刻消费
            //                                mHelper.consumeAsync(purchase, mConsumeFinishedListener);
            //                            } catch (IabHelper.IabAsyncInProgressException e) {
            //                                complain("Error consuming gas. Another async operation in progress.");
            ////                                setWaitScreen(false);
            //                                return;
            //                            }
            //                        }
            //                        else if (purchase.getSku().equals(SKU_PREMIUM)) {
            //                            // bought the premium upgrade!
            //                            Log.d(TAG, "Purchase is premium upgrade. Congratulating user.");
            //                            alert("Thank you for upgrading to premium!");
            //                            mIsPremium = true;
            //                            updateUi();
            //                            setWaitScreen(false);
            //                        }
            //                        else if (purchase.getSku().equals(SKU_INFINITE_GAS_MONTHLY)
            //                                || purchase.getSku().equals(SKU_INFINITE_GAS_YEARLY)) {
            //                            // bought the infinite gas subscription
            //                            Log.d(TAG, "Infinite gas subscription purchased.");
            //                            alert("Thank you for subscribing to infinite gas!");
            //                            mSubscribedToInfiniteGas = true;
            //                            mAutoRenewEnabled = purchase.isAutoRenewing();
            //                            mInfiniteGasSku = purchase.getSku();
            //                            mTank = TANK_MAX;
            //                            updateUi();
            //                            setWaitScreen(false);
            //                        }
        }
    };


    /**
     * 消费完成
     *
     * @param result   消费状态
     * @param purchase 消费的商品
     */

    IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener() {
        @Override
        public void onConsumeFinished(Purchase purchase, IabResult result) {
            if (result.isFailure()) {
                complain("Error purchasing: " + result.getMessage());
                //setWaitScreen(false);
                return;
            }
            ToastUtil.showToast(Zy_GooglePay.this, purchase.getSku() + "消费成功");
            queryPurchaseProducts("inapp");
        }
    };


    /**
     * Verifies the developer payload of a purchase.
     */
    boolean verifyDeveloperPayload(Purchase p) {
        String payload = p.getDeveloperPayload();

        /*
         * TODO: verify that the developer payload of the purchase is correct. It will be
         * the same one that you sent when initiating the purchase.
         *
         * WARNING: Locally generating a random string when starting a purchase and
         * verifying it here might seem like a good approach, but this will fail in the
         * case where the user purchases an item on one device and then uses your app on
         * a different device, because on the other device you will not have access to the
         * random string you originally generated.
         *
         * So a good developer payload has these characteristics:
         *
         * 1. If two different users purchase an item, the payload is different between them,
         *    so that one user's purchase can't be replayed to another user.
         *
         * 2. The payload must be such that you can verify it even when the app wasn't the
         *    one who initiated the purchase flow (so that items purchased by the user on
         *    one device work on other devices owned by the user).
         *
         * Using your own server to store and verify developer payloads across app
         * installations is recommended.
         */

        return true;
    }

    void complain(String message) {
        Log.e(TAG, "**** TrivialDrive Error: " + message);
        alert("Error: " + message);
    }

    void alert(String message) {
        AlertDialog.Builder bld = new AlertDialog.Builder(this);
        bld.setMessage(message);
        bld.setNeutralButton("OK", null);
        Log.d(TAG, "Showing alert dialog: " + message);
        bld.create().show();
    }


    //监听 商品 查询结果
    IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
        public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
            Log.d(TAG, "Query inventory finished.");

            // Have we been disposed of in the meantime? If so, quit.
            if (mHelper == null)
                return;

            // Is it a failure?
            if (result.isFailure()) {
                //                complain("Failed to query inventory: " + result);
                LogHelper.i(TAG, "查询失败");
                return;
            }
            LogHelper.i(TAG, result.toString());
            LogHelper.i(TAG, "查询成功");
            LogHelper.i(TAG, inventory.toString());

            Log.d(TAG, "Query inventory was successful.");

            /*
             * Check for items we own. Notice that for each purchase, we check
             * the developer payload to see if it's correct! See
             * verifyDeveloperPayload().
             */

            // Do we have the premium upgrade?
            Purchase premiumPurchase = inventory.getPurchase(SKU_PREMIUM);
            //            mIsPremium = (premiumPurchase != null && verifyDeveloperPayload(premiumPurchase));
            //            Log.d(TAG, "User is " + (mIsPremium ? "PREMIUM" : "NOT PREMIUM"));

            // First find out which subscription is auto renewing
            //订阅更新
           /* Purchase gasMonthly = inventory.getPurchase(SKU_INFINITE_GAS_MONTHLY);
            Purchase gasYearly = inventory.getPurchase(SKU_INFINITE_GAS_YEARLY);
            if (gasMonthly != null && gasMonthly.isAutoRenewing()) {
                mInfiniteGasSku = SKU_INFINITE_GAS_MONTHLY;
                mAutoRenewEnabled = true;
            } else if (gasYearly != null && gasYearly.isAutoRenewing()) {
                mInfiniteGasSku = SKU_INFINITE_GAS_YEARLY;
                mAutoRenewEnabled = true;
            } else {
                mInfiniteGasSku = "";
                mAutoRenewEnabled = false;
            }*/

            // The user is subscribed if either subscription exists, even if neither is auto
            // renewing 订阅
            /*mSubscribedToInfiniteGas = (gasMonthly != null && verifyDeveloperPayload(gasMonthly))
                    || (gasYearly != null && verifyDeveloperPayload(gasYearly));
            Log.d(TAG, "User " + (mSubscribedToInfiniteGas ? "HAS" : "DOES NOT HAVE")
                    + " infinite gas subscription.");
            if (mSubscribedToInfiniteGas) mTank = TANK_MAX;*/

            // Check for gas delivery -- if we own gas, we should fill up the tank immediately
            //            Purchase gasPurchase = inventory.getPurchase(SKU_GAS);
            //            if (gasPurchase != null && verifyDeveloperPayload(gasPurchase)) {
            //                Log.d(TAG, "We have gas. Consuming it.");
            //                try {
            //                    mHelper.consumeAsync(inventory.getPurchase(SKU_GAS), mConsumeFinishedListener);
            //                } catch (IabHelper.IabAsyncInProgressException e) {
            //                    complain("Error consuming gas. Another async operation in progress.");
            //                }
            //                return;
            //            }

            //            updateUi();
            //            setWaitScreen(false);
            //            Log.d(TAG, "Initial inventory query finished; enabling main UI.");
        }
    };


    /*
     * 当ScrollView 与 LiseView 同时滚动计算高度的方法
     * 设置listview 的高度
     * 参数：listivew的findviewbyid
     * */
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        try {
            // 获取ListView对应的Adapter
            android.widget.ListAdapter listAdapter = listView.getAdapter();
            if (listAdapter == null) {
                return;
            }

            int totalHeight = 0;
            for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
                // listAdapter.getCount()返回数据项的数目
                View listItem = listAdapter.getView(i, null, listView);
                // 计算子项View 的宽高
                listItem.measure(0, 0);
                // 统计所有子项的总高度
                totalHeight += listItem.getMeasuredHeight();
            }
            ViewGroup.LayoutParams params = listView.getLayoutParams();
            params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
            // listView.getDividerHeight()获取子项间分隔符占用的高度
            // params.height最后得到整个ListView完整显示需要的高度
            listView.setLayoutParams(params);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
